<script setup lang="ts">
import { reactive, defineProps, defineEmits, watch } from 'vue'
import { getApi, updateApi, createApi } from '/@/api/mes/process'
import { useInModal } from '/@/hooks/useModal'
import { useInsertSucessMessage, useUpdateSucessMessage } from '/@/hooks/useMessage'

const props = defineProps(({
  id: String
}))

const emits = defineEmits(['change'])

const modal = useInModal()

const formProps = reactive<FormMakerProps>({
  name: 'processForm',
  model: {
    code: '',
    name: ''
  },
  options: [
    { field: "code", label: "工序编码", required: true },
    { field: "name", label: "工序名称", required: true },
  ]
})

watch(() => props.id, (id: string) => {
  if (id) {
    modal.loading(true)
    getApi(id)
      .then(res => {
        Object.assign(formProps.model, res.data)
      })
      .finally(() => modal.loading(false))
  }
}, { immediate: true })

const viewLayout: ViewLayoutProps = {
  buttons: [
    {
      title: '确定', type: 'primary', onClick: async () => {
        modal.loading(true)
        try {
          if (props.id) {
            const { succeeded } = await updateApi(formProps.model)
            if (succeeded) {
              useUpdateSucessMessage()
            }
          } else {
            const { succeeded } = await createApi(formProps.model)
            succeeded && useInsertSucessMessage()
          }

          emits('change')
        }
        finally {
          modal.loading(false)
        }
      }
    },
    { title: '取消', onClick: () => modal.close() },
  ]
}



</script>

<template>
  <ViewLayout v-bind="viewLayout">
    <FormMaker v-bind="formProps" />
  </ViewLayout>
</template>